package com.grass.cropTradingCenter.repository;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.grass.cropTradingCenter.domain.repository.UserStarRepository;
import com.grass.cropTradingCenter.mapper.UserStarMapper;
import com.grass.cropTradingCenter.pojo.entity.UserStar;
import com.grass.cropTradingCenter.pojo.po.StarType;
import com.grass.cropTradingCenter.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserStarRepositoryImpl implements UserStarRepository {
    @Autowired
    UserStarMapper userStarMapper;

    @Override
    public boolean isStart(StarType starType) {
        LambdaQueryWrapper<UserStar> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserStar::getOtherId, starType.getOtherId());
        queryWrapper.eq(UserStar::getOtherType, starType.getStarType());
        queryWrapper.eq(UserStar::getUserId, SecurityUtils.getUserId());
        Integer integer = userStarMapper.selectCount(queryWrapper);
        return integer >= 1;
    }

    @Override
    public void checkStarStatus(StarType vo) {
        // 要关注但是没有关注
        if(vo.getIsStar() && !isStart(vo)){
            UserStar userStar = new UserStar();
            userStar.setUserId(SecurityUtils.getUserId());
            userStar.setOtherType(vo.getStarType());
            userStar.setOtherId(vo.getOtherId());
            userStarMapper.insert(userStar);
            return;
        }
        LambdaQueryWrapper<UserStar> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserStar::getOtherId, vo.getOtherId());
        queryWrapper.eq(UserStar::getOtherType, vo.getStarType());
        queryWrapper.eq(UserStar::getUserId, SecurityUtils.getUserId());
        userStarMapper.delete(queryWrapper);
    }

    /**
     * 获取收藏列表
     * @param type 1--商品  2--店铺
     * @return
     */
    @Override
    public List<UserStar> getStarByUserAndType(int type) {
        LambdaQueryWrapper<UserStar> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserStar::getUserId, SecurityUtils.getUserId())
                .eq(UserStar::getOtherType, type);
        return userStarMapper.selectList(queryWrapper);
    }

    /**
     *
     * @param type 1--商品  2--店铺
     * @return
     */
    @Override
    public int getStarNum(int type) {
        LambdaQueryWrapper<UserStar> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserStar::getUserId, SecurityUtils.getUserId())
                .eq(UserStar::getOtherType, type);
        return userStarMapper.selectCount(queryWrapper);
    }
}
